const jwt = require("jsonwebtoken");

module.exports = (options, app) => {
	return async function auth(ctx, next) {
		if (!options.whiteList.includes(ctx.url)) {
			const authorization = ctx.headers.authorization;
			if (!authorization) {
				ctx.body = {
					code: 401,
					message: "没有权限"
				};
			} else {
				const token = authorization.replace("Bearer ", "");
				// 验证 token
				try {
					const user = jwt.verify(token, app.config.PUBLIC_KEY, {
						algorithms: ["RS256"]
					});
					ctx.user = user;
					await next();
				} catch (error) {
					ctx.body = {
						code: 401,
						message: "无效token"
					};
				}
			}
		} else {
			await next();
		}
	};
};
